<template>
  <div class="details">
    <div class="details-content">
      <div class="details-content-left">
        <el-select class="projectValue" 
          v-model="headerForm.projectId" 
          placeholder="请选择"
          @change="headerSearch"
        >
          <el-option 
            v-for="item in projectOption" 
            :key="item.id" 
            :label="item.projectName" 
            :value="item.id" 
          />
        </el-select>
        <div class="roomData">
          <div 
            v-for="(item, index) in roomList.list" 
            :key="item.id"
            :class="`roomItem ${roomActive == item.id ? 'roomActive' : ''}`" 
            @click="roomListClick(item.id)"
          >
            <div>{{ item.houseNum }}</div>
          </div>
        </div>
      </div>
      <div class="details-content-right">
        <div class="content-right-tabs">
          <el-radio-group v-model="electricWaterVapor"  @change="electricWaterVaporSearch">
            <el-radio-button label="电表" value="电" />
            <el-radio-button label="水表" value="水" />
            <el-radio-button label="气表" value="气" />
            <el-radio-button label="监控终端" value="终端" />
          </el-radio-group>
        </div>
        <div class="content-right-brake">
          <img v-if="equipImage":src="equipImage" alt="设备图片">
          <div v-else class="no-img">暂无图片</div>
          <div v-if="electricWaterVapor !== '终端'">
            <div class="brake-item">
              <p style="color: #03CCA1;">{{ currentValue }}</p>
              <p :title="`当前示数(${unit})`">当前示数({{ unit }})</p>
            </div>
            <div class="brake-item">
              <p>{{ totalValue }}</p>
              <p :title="`累计${electricWaterVapor}量(${unit})`">累计{{electricWaterVapor}}量({{ unit }})</p>
            </div>
            <div class="brake-item">
              <p>{{ todayValue }}</p>
              <p>当天{{electricWaterVapor}}量({{ unit }})</p>
            </div>
          </div>
          <div v-else>
            <div class="brake-item">
              <div>设备MAC: {{ detailData.ectEquipMAcCode }}</div>
              <p style="color: #03CCA1;">{{ detailData.ectSwitchStatus }}</p>
              <p :title="`当前开关状态`" style="margin: 0; font-size: 12px;">当前开关状态</p>
            </div>
            <div class="brake-item">
              <p>{{ detailData.ectPkgVersion }}</p>
              <p :title="`当前软件版本`">当前软件版本</p>
            </div>
            <div class="brake-item">
              <p>{{ detailData.ectTempReadValue }}</p>
              <p>端子温度(℃)</p>
            </div>
            <div style="float: right; padding: 45px 56px 0 0;">
              <el-button type="primary" @click="onSwitch">强制{{ detailData.ectSwitchStatus === '合闸' ? '开闸' : '合闸' }}</el-button>
            </div>
          </div>
          <!-- <div class="brake-button">
            <el-button type="primary" @click="brakeButtonClick('强制合闸')">强制合闸</el-button>
            <el-button color="#5FB3FF" @click="brakeButtonClick('强制分闸')">强制分闸</el-button>
          </div> -->
        </div>
        <div class="content-right-message">
          <el-tabs 
            v-model="tabMessage" 
            class="demo-tabs" 
            @tab-click="tabMessageClick"
          >
            <el-tab-pane :label="electricWaterVapor !== '终端' ? '用能信息' : '监控变化曲线'" name="1">
              <div 
                class="tab-item" 
                ref="dailyTrendRef"
              />
            </el-tab-pane>
            <el-tab-pane label="变量信息" name="2">
              <VariableInfo v-if="tabMessage == '2' && equipId" :equip-id="equipId"/>
            </el-tab-pane>
            <el-tab-pane v-if="electricWaterVapor == '终端'" label="开合闸记录" name="3">
              <VariableInfo2 v-if="tabMessage == '3' && equipId" :equip-id="equipId"/>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue';
import * as echarts from 'echarts';
import { useRoute } from 'vue-router'
import VariableInfo from './components/VariableInfo.vue'
import VariableInfo2 from './components/VariableInfo2.vue'
import elecImg from '@/assets/images/default-elec.png'
import waterImg from '@/assets/images/default-water.png'
import gasImg from '@/assets/images/default-gas.png'
import { getProjectList, getMonitorList, goSwitch, getMonitorDetail } from '@/api/settle';

const route = useRoute()
const projectOption = ref([])
const headerForm = ref({
  projectId: null,
  type: 1, 
})
const detailData = ref({})
const roomList = reactive({
  list: [] as any
})
const roomActive = ref('') 

const dailyTrendRef = ref(''); 
const dailyTrendData = ref([ // 信息趋势图数据
  {
    name: "00时",
    nameValue: 0,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "01时",
    nameValue: 1,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "02时",
    nameValue: 2,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "03时",
    nameValue: 3,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "04时",
    nameValue: 4,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "05时",
    nameValue: 5,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "06时",
    nameValue: 6,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "07时",
    nameValue: 7,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "08时",
    nameValue: 8,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "09时",
    nameValue: 9,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "10时",
    nameValue: 10,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "11时",
    nameValue: 11,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "12时",
    nameValue: 12,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "13时",
    nameValue: 13,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "14时",
    nameValue: 14,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "15时",
    nameValue: 15,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "16时",
    nameValue: 16,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "17时",
    nameValue: 17,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "18时",
    nameValue: 18,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "19时",
    nameValue: 19,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "20时",
    nameValue: 20,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "21时",
    nameValue: 21,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "22时",
    nameValue: 22,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "23时",
    nameValue: 23,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  },
  {
    name: "24时",
    nameValue: 24,
    elecValue: null,
    waterValue: null,
    gasValue: null,
    etcValue: null
  }
]);

const electricWaterVapor = ref('电')
const tabMessage = ref('1')

// 当前示数
const currentValue = computed(() => {
  if (electricWaterVapor.value == '电') {
    return detailData.value?.elecReadValue ?? '--'
  } else if (electricWaterVapor.value == '水') {
    return detailData.value?.waterReadValue ?? '--'
  } else {
    return detailData.value?.gacReadValue ?? '--'
  }
})

// 累计值
const totalValue = computed(() => {
  if (electricWaterVapor.value == '电') {
    return detailData.value?.totalElec ?? '--'
  } else if (electricWaterVapor.value == '水') {
    return detailData.value?.totalWater ?? '--'
  } else {
    return detailData.value?.totalGas ?? '--'
  }
})

// 当天值
const todayValue = computed(() => {
  if (electricWaterVapor.value == '电') {
    return detailData.value?.dayElec ?? '--'
  } else if (electricWaterVapor.value == '水') {
    return detailData.value?.dayWater ?? '--'
  } else {
    return detailData.value?.dayGas ?? '--'
  }
})

// 单位
const unit = computed(() => {
  if (electricWaterVapor.value == '电') {
    return 'kW·h'
  } else if (electricWaterVapor.value == '水') {
    return 't'
  } else if (electricWaterVapor.value == '气') {
    return 'm³'
  } else {
    return '℃'
  }
})


// 设备Id
const equipId = computed(() => {
  if (electricWaterVapor.value == '电') {
    return detailData.value?.emEquipId ?? ''
  } else if (electricWaterVapor.value == '水') {
    return detailData.value?.wmEquipId ?? ''
  } else if (electricWaterVapor.value == '气') {
    return detailData.value?.gmEquipId ?? ''
  } else {
    return detailData.value?.ectEquipId ?? ''
  }
})
// 设备图片
const equipImage = computed(() => {
  if (electricWaterVapor.value == '电') {
    return detailData.value?.emEquipImg ?? elecImg
  } else if (electricWaterVapor.value == '水') {
    return detailData.value?.wmEquipImg ?? waterImg
  } else if (electricWaterVapor.value == '气') {
    return detailData.value?.gmEquipImg ?? gasImg
  } else {  
    return elecImg
  }
})
// flag：搜索出来后是否默认选中第一个
const headerSearch = (flag = false, houseId = null) => { 
  getMonitor(flag, houseId)
}

const onSwitch = () => {
  // console.log('强制开/合闸')
  const params = {
    equipId: equipId.value,
    status: detailData.value.ectSwitchStatus === '合闸' ? 2 : 1
  }
  goSwitch(params)
    .then((res)=> {
      console.log(res)
    })
    .catch((err)=> {
      console.log(err)
    })
}

// 获取房间列表
const getMonitor = (flag = false, houseId = null) => {
  getMonitorList(headerForm.value).then((res)=>{
    roomList.list = res.data ?? []
    // 从房间监控跳转过来的
    if (flag && houseId != null) {
      roomListClick(houseId)
    } else if (flag && roomList.list.length > 0) { // 点击详情菜单首次加载的
      roomListClick(roomList.list[0].id)
    }
  })
  .catch((err)=> {
    roomList.list.length = 0
  })
}

// 房间列表点击事件
const roomListClick = (houseId: any) => { 
  roomActive.value = houseId;
  getMonitorDetail({houseId: houseId})
    .then((res)=>{
      detailData.value = res.data ?? {}
      const list = detailData.value.usageMsgList ?? []
      // 图表数据赋值
      dailyTrendData.value.forEach(item => {
        item.elecValue = null
        item.waterValue = null
        item.gasValue = null
        item.etcValue = null
      })

      list.forEach(item => {
        let ind = dailyTrendData.value.findIndex(v => v.nameValue == item.hours)
        if (ind != -1) {
          dailyTrendData.value[ind].elecValue = item.hourElec ?? null
          dailyTrendData.value[ind].waterValue = item.hourWater ?? null
          dailyTrendData.value[ind].gasValue = item.hourGas ?? null
          dailyTrendData.value[ind].etcValue = item.ectTempNow ?? null
        }
      })
      drawChart()  
    })
    .catch((err)=>{
      detailData.value = {}
      dailyTrendData.value.forEach(item => {
        item.elecValue = null
        item.waterValue = null
        item.gasValue = null
        item.etcValue = null
      })
    })
}

// 信息趋势图
const drawChart = () => {
  const chartInstance = echarts.init(dailyTrendRef.value);
  let xAxisData = dailyTrendData.value.map(v => v.name);
  let yAxisData1 = dailyTrendData.value.map(v => {
    if (electricWaterVapor.value == '电') {
      return v.elecValue
    } else if (electricWaterVapor.value == '水') {
      return v.waterValue
    } else if (electricWaterVapor.value == '气') {
      return v.gasValue
    } else {
      return v.etcValue
    }
  });
  // 数据是否都为空
  let isEmpty = yAxisData1.filter(v => v != null).length == 0
  const color = ["#02C49B", "#FAB743"]

  const option = {
    color: color,
    tooltip: {
      trigger: "axis",
    },
    grid: {
      top: 50,
      right: 14,
      left: isEmpty ? 20 : 0,
      bottom: 0,
      containLabel: true
    },
    xAxis: [{
      type: "category",
      boundaryGap: false,
      axisLabel: {
        color: "#B0B3B7"
      },
      axisLine: {
        lineStyle: {
          color: "#F5F7FA"
        }
      },
      axisTick: {
        show: false
      },
      data: xAxisData
    }],
    yAxis: [{
      type: "value",
      name: unit.value,
      axisLabel: {
        color: "#B0B3B7"
      },
      nameTextStyle: {
        color: "#B0B3B7",
        fontSize: 12,
        lineHeight: 40
      },
      splitLine: {
        lineStyle: {
          type: "solid",
          color: "#F5F7FA"
        }
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    }],
    series: [{
      name: "今日",
      type: "line",
      smooth: true,
      // showSymbol: false,/
      areaStyle: {
        color: new echarts.graphic.LinearGradient(
          0,
          0,
          0,
          1,
          [{
            offset: 0,
            color: hexToRgba(color[0], 0.3)
          },
          {
            offset: 1,
            color: hexToRgba(color[0], 0.1)
          }
          ],
          false
        ),
        shadowColor: hexToRgba(color[0], 0.1),
        shadowBlur: 10,
      },
      data: yAxisData1
    }]
  };
  chartInstance.setOption(option);
  chartInstance.resize();
}

const hexToRgba = (hex: string, opacity: any) => {
  let rgbaColor = "";
  let reg = /^#[\da-f]{6}$/i;
  if (reg.test(hex)) {
    rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
      "0x" + hex.slice(3, 5)
    )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
  }
  return rgbaColor;
}

const electricWaterVaporSearch = (e: string) => { // 电水气tabs切换
  tabMessage.value = '1'
  setTimeout(() => {
    drawChart()
  }, 10)
}

// 用能信息tabs点击
const tabMessageClick = (tab:any) => {
  if (tab.paneName == '1') {
    setTimeout(() => {
      drawChart()
    }, 10)
  }
}

const pageInit = () => {
  getProjectList()
    .then((res: any)=>{
      projectOption.value = res.data ?? []
      if (projectOption.value.length > 0) {
        if (route.query.projectId) {
          headerForm.value.projectId = Number(route.query.projectId)
          headerSearch(true, route.query.houseId)
        } else {
          headerForm.value.projectId = projectOption.value[0].id
          headerSearch(true)
        }
      }
    })
}

onMounted(() => {
  pageInit()
})

</script>

<style lang="scss" scoped>
.details {
  padding: 20px;
  background: #F2FBF9;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  // height: calc(100vh - 50px);
}

.details-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  height: 40px;

  .details-header-title {
    font-weight: bold;
    color: #333333;
    font-size: 16px;
    display: flex;
    align-items: center;

    .el-icon {
      margin-right: 4px;
    }
  }
}

.details-content {
  position: relative;
  min-height: calc(100vh - 130px);
  padding: 24px 16px 24px 0px;
  background: #FFFFFF;
  box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.06);
  border-radius: 8px;
  .details-content-left {
    position: absolute;
    width: 216px;
    height: 100%;
    top: 0;
    bottom: 0;
    left: 0;
    border-right: 1px solid #EFF5F4;
    .roomData {
      overflow: auto;
    }
    .projectValue {
      width: 184px;
      margin: 16px 16px 11px;
    }

    .roomItem {
      width: 100%;
      height: 32px;
      line-height: 32px;
      cursor: pointer;
      div {
        position: relative;
        margin-left: 40px;
        &::after {
          position: absolute;
          top: 12px;
          left: -16px;
          width: 8px;
          height: 8px;
          border-radius: 4px;
          border: 1px solid #C5C8C7;
          content: '';
        }
      }
    }

    .roomActive {
      background: rgba(204, 245, 236, 0.4);
      border-right: 1px solid #03CCA1;
      div {
        color: #00AA86;

        &::after {
          border-color: #03CCA1;
          background: #03CCA1;
        }
      }
    }
  }

  .details-content-right {
    margin-left: 216px;
    padding-left: 15px;
    .content-right-tabs {
      margin-bottom: 11px;
    }

    .content-right-brake {
      margin-bottom: 6px;
      border-radius: 8px;
      padding: 7px 2px 7px 64px;
      height: 134px;
      background: url(@/assets/images/monitoringDetailsBackground.png) 0 0 no-repeat;
      background-size: cover;
      > img {
        width: 150px;
        height: 120px;
        float: left;
      }
      .no-img {
        width: 150px;
        height: 120px;
        border-radius: 10px;
        background: #04cca1;
        text-align: center;
        line-height: 120px;
        color: #9ba8a1;
        float: left;
      }
      .brake-item {
        position: relative;
        float: left;
        text-align: center;
        height: 43px;
        margin-top: 35px;
        border-right: 1px solid #d0d3d3;
        > div {
          position: absolute;
          top: -25px;
          left: 10px;
          width: 300px;
          text-align: left;
          + p {
            font-weight: bold;
            font-size: 20px!important;
            margin: 0 0 5px!important;
          }
        }
        p {
          padding: 0 50px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        p:nth-child(1) {
          margin: 0 0 5px;
          font-weight: bold;
          font-size: 20px;
        }

        p:nth-child(2) {
          margin: 0;
          font-size: 12px;
        }
      }

      .brake-item:nth-child(4) {
        border-right: 0px;
      }

      .brake-button {
        float: right;
        margin-top: 45px;
        .el-button {
          color: #FFFFFF;
        }
      }
    }

    .content-right-message {
      width: 100%;
      .tab-item {
        width: 99%;
        height: 370px;
      }
      :deep(.el-tabs__header) {
        width: 100%;

        .el-tabs__item.is-active,
        .el-tabs__item:hover {
          color: #03CCA1;
        }

        .el-tabs__active-bar {
          background-color: #03CCA1;
        }
      }
    }
  }
}
@media screen and (max-width: 1560px) {
  .details-content-right {
    .content-right-brake {
      .brake-item {
        p {
          padding: 0 30px!important;
        }
      }
    }
  }
}
</style>